package cn.jingyuan.bee.enums.spring.convert;

import cn.jingyuan.bee.enums.EnumInteger;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;


/**
 * 自定义 {@link Integer} 类型枚举转换
 */
public class EnumIntegerConverter implements ConverterFactory<Integer, EnumInteger> {

    @Override
    public <T extends EnumInteger> Converter<Integer, T> getConverter(Class<T> targetType) {
        return new StringToEnum(targetType);
    }

    private class StringToEnum<T extends EnumInteger> implements Converter<Integer, T> {

        private final Class clazz;

        public StringToEnum(Class<T> targetType) {
            clazz = targetType;
        }

        @Override
        public T convert(Integer source) {
            Enum value = EnumInteger.from(clazz, source);
            if (null == value) {
                return null;
            }
            return (T) value;
        }

    }

}
